// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.internal.services;

import java.util.List;

import lichen.entities.forum.Treeable;
import lichen.services.IMoveTreeNodeProcessor;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 * 向下移动的处理程序
 * 
 * @author <a href="mailto:jun.tsai@bjmaxinfo.com">Jun Tsai</a>
 * @version $Revision: 111 $
 * @since 0.0.1
 */
class MoveDownProcessor extends AbstractMoveTreeNodeProcessor implements
		IMoveTreeNodeProcessor {

	private int moveBlockLeftStart = 0;

	private int moveBlockLeftEnd = Integer.MAX_VALUE;

	private int offset = 0;

	@Override
	protected void appendQueryReplaceNodeCriteria(DetachedCriteria criteria) {
		
		/*
		 * add restrictions:
		 * where right>self.right and right<parent.right order by left
		 */
		criteria.add(Restrictions.gt(Treeable.RIGHT_PRO_NAME, getCurrentNode().getRight()))
				.add(Restrictions.lt(Treeable.RIGHT_PRO_NAME, getParentNode().getRight()));
		criteria.addOrder(Order.asc(Treeable.LEFT_PRO_NAME));

	}

	@Override
	protected void fetchMoveBlockInfo(List list) {
		if (list.size() == 0) { // 未找到了移动的位置，说明已经溢出
			offset = (getParentNode().getRight() - 1)
					- getCurrentNode().getRight();
			moveBlockLeftStart = getCurrentNode().getRight() + 1;
			moveBlockLeftEnd = getParentNode().getRight();
		} else {// 找到了移动的位置
			Treeable replaceNode = (Treeable) list.get(0);
			offset = replaceNode.getRight() - getCurrentNode().getRight();
			moveBlockLeftStart = getCurrentNode().getRight() + 1;
			moveBlockLeftEnd = replaceNode.getRight();
		}

	}

	@Override
	protected int getMoveBlockLeftEnd() {
		return this.moveBlockLeftEnd;
	}

	@Override
	protected int getMoveBlockLeftStart() {
		return this.moveBlockLeftStart;
	}

	@Override
	protected int getOffset() {
		return this.offset;
	}

	@Override
	protected int getUpdateWidth() {
		return getCurrentNode().getLeft() - getCurrentNode().getRight() - 1;
	}

	@Override
	protected Treeable constructRootNode() {
		Treeable rootNode=newTreeable();
		
		rootNode.setLeft(0);

		long rowCount = (Long) getHibernateTemplate().find("select count(*) from " + getTreeClassName()).iterator().next();
		rootNode.setRight((int) (rowCount * 2 + 1));

		return rootNode;
	}
}
